import {
	createStore
} from 'vuex'
import config from '@/config.js'

import {
	getToken,
	setToken,
	removeToken,
	clearStorage
} from '../utils/auth'

const getDefaultState = () => {
	return {
		token: getToken(),
		isLogin: getToken() ? true : false,
		version: "v1.0.0",
		userInfo: {}
	}
}

const state = getDefaultState()

const mutations = {
	SET_TOKEN: (state, token) => {
		state.token = token
	},
	SET_USERINFO: (state, data) => {
		state.userInfo = data
	}
}

const actions = {
	login({
		commit
	}, fun) {
		return new Promise((resolve, reject) => {
			fun().then(data => {
				commit('SET_USERINFO', data)
				resolve(data)
			}).catch(error => {
				removeToken() // must remove  token  first
				reject(error)
			})
		})
	},
	logout({
		commit
	}, fun) {
		return new Promise((resolve, reject) => {
			try {
				commit('SET_USERINFO', {})
				commit('SET_TOKEN', "")
				clearStorage()
				resolve({})
			} catch (error) {
				clearStorage() // must remove  token  first
				reject(error)
			}
		})
	}
}

const store = createStore({
	state,
	mutations,
	actions,
	modules: {}
})

const storeName = 'weapp_' + config.Unique

export function install() {
	if (!store.hasModule(storeName)) {
		store.registerModule(storeName, {
			namespaced: true,
			state: state,
			mutations,
			actions,
			getters: {
				getState: (state) => (value) => {
					return state[value];
				},
				isLogin: (state) => (value) => {
					return getToken() ? true : false
				}
			}
		})
	}
}

export function uninstall() {
	if (store.hasModule(storeName)) {
		store.unregisterModule(storeName)
	}
}

export function getStore() {
	install();
	return {
		state: store.state[storeName],
		commit(type, payload, options) {
			type = storeName + '/' + type
			return store.commit(type, payload, options)
		},
		dispatch(type, payload) {
			type = storeName + '/' + type
			return store.dispatch(type, payload)
		},
		getter(value) {
			let type = storeName + '/getState';
			return store.getters[type](value)
		},
		isLogin() {
			let type = storeName + '/isLogin';
			return store.getters[type]();
		}
	}
}